import requests,os
from ep import ep_decode
from threading import Thread
from pathDecode import path_decode
from login import login
session = login()
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36"}
class xmly(object):
    def __init__(self, albumId):
        self.albumId = albumId
        self.t_list = []
        self.run_t = 7
        self.save_dir = r"D:\喜马拉雅"
        self.start_index = 1
        self.get_detail()
        self.m4a_path = os.path.join(self.save_dir,'m4a')
        self.mp3_path = os.path.join(self.save_dir,'mp3')
        if not os.path.exists(self.m4a_path):
            os.makedirs(self.m4a_path)
        if not os.path.exists(self.mp3_path):
            os.makedirs(self.mp3_path)
        self.update_index() #更新开始位置
        self.get_tracks_list()
        for t in self.t_list:
            t.join()

    def get_tracks_list(self):
        albumId = self.albumId
        for pageNum in range(1, 10):
            url = "https://www.ximalaya.com/revision/album/v1/getTracksList?albumId=%s&pageNum=%s&pageSize=1000" % (
            albumId, pageNum)
            data = requests.get(url, headers=headers, verify=False).json()
            if data['ret'] == 200:
                if data['data']['tracks'] != []:
                    for trackItem in data['data']['tracks']:
                        if trackItem['index'] >= self.start_index:
                            self.get_m4a_url(trackItem)
                else:
                    break

    def get_m4a_url(self, trackItem):
        trackId = trackItem["trackId"]
        title = str(trackItem['index']) + "-" + trackItem['title']
        url = "https://mpay.ximalaya.com/mobile/track/pay/%s/?device=pc" % trackId
        data = session.get(url,verify=False).json()
        if data['ret'] == 0:
            # print("接口1")
            fileId = data['fileId']
            seed = data['seed']
            ep = data['ep']
            domain = data['domain']
            apiVersion = data['apiVersion']
            arg = ep_decode(ep)
            arg['duration'] = data['duration']
            filename = path_decode(seed,fileId)
            url = domain + '/download/'+ apiVersion +"/"+ filename+'?'
            for key,value in arg.items():
                url = url + key +'=' +str(value)+'&'
            else:
                url = url[:-1]
        else:
            print("接口2")
            url = "https://www.ximalaya.com/revision/play/v1/audio?id=%s&ptype=1" % trackId
            data = session.get(url,verify=False,headers=headers).json()
            url = data['data']['src']
        t = Thread(target=self.download_m4a,args=(url,title))
        t.start()
        self.t_list.append(t)
        if len(self.t_list) == self.run_t:
            for t in self.t_list:
                t.join()
            self.t_list = []

    def download_m4a(self, url, title):
        title = title.replace(" ", "-").replace('|', '-').replace(":", "-")
        data = requests.get(url, verify=False).content
        filename = os.path.join(self.m4a_path, title + '.m4a')
        print(data)